import { reqGetCode, reqUserRegister, reqUserLogin, reqUserInfo, reqUserLogout } from '@/api'
import { setToken } from '@/utils/token'

const actions = {
    // 获取验证码
    async getCode({ commit }, phone) {
        let result = await reqGetCode(phone);
        if (result.code == 200) {
            commit('GETCODE', result.data)
        } else {
            return Promise.reject(new Error('fail'))
        }
    },
    // 用户注册
    async userRegister({ commit }, user) {
        let result = await reqUserRegister(user);
        if (result.code == 200) {
            return 'ok'
        } else {
            alert(result.message);
            return Promise.reject(new Error('fail'))
        }
    },
    // 登陆业务（由服务器下发token--令牌，用户的唯一标识）
    async userLogin({ commit }, data) {
        let result = await reqUserLogin(data)
        // 通过token找服务器对用户信息进行展示
        if (result.code == 200) {
            // 登陆成功，但是vuex中的token一刷新就没了，不是持久存储
            commit('USERLOGIN', result.data.token);
            // 将 token 本地存储
            setToken(result.data.token)
            return 'ok'
        } else {
            return Promise.reject(new Error('fail'))
        }
    },
    // 获取用户信息
    async getUserInfo({ commit }) {
        let result = await reqUserInfo();
        if (result.code == 200 || result.message == '未登陆') {
            // 提交用户信息
            commit('GETUSERINFO', result.data)
            return 'ok'
        } else {
            return Promise.reject(new Error('fail'))
        }
    },
    // 登出
    async userLogout({ commit }) {
        // 通知服务器清楚token
        let result = await reqUserLogout()
        if (result.code == 200) {
            // commit 清除 userInfo和本地token 登本地数据
            // 注意： actions中不能操作state，所以要到mutation中清除state
            commit('CLRAR');
            return 'ok'
        } else {
            return Promise.reject(new Error('fail'))
        }
    },
}

const mutations = {
    GETCODE(state, code) {
        state.code = code;
    },
    USERLOGIN(state, token) {
        state.token = token;
    },
    GETUSERINFO(state, userInfo) {
        state.userInfo = userInfo || {};
    },
    CLRAR() {
        state.userInfo = {};
        state.token = '';
        localStorage.removeItem('TOKEN');
    }
}

const state = {
    code: '',
    token: localStorage.getItem('TOKEN'),
    userInfo: {},
}

const getters = {}

export default {
    actions, mutations, state, getters
}